package com.central.scheduler.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.common.utils.UserRoleUtil;
import com.central.scheduler.api.service.IProcessInstanceService;
import com.central.scheduler.common.enums.ReleaseState;
import com.central.scheduler.dao.mapper.*;
import com.central.scheduler.dao.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@Slf4j
@Service
public class ProcessInstanceServiceImpl extends SuperServiceImpl<ProcessInstanceMapper, ProcessInstance> implements IProcessInstanceService {

    @Override
    public PageResult<ProcessInstance> queryProcessInstances(Map<String, Object> params) {
        Page<ProcessInstance> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
        List<ProcessInstance> list = baseMapper.queryProcessInstances(page, params);
        long total = page.getTotal();
        return PageResult.<ProcessInstance>builder().data(list).code(0).count(total).build();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result delProcessInstance(SysUser user, Long processInstanceId) {
        ProcessInstance processInstance = baseMapper.selectById(processInstanceId);
        if (processInstance != null) {
            //检查用户是否有权限
            if (!checkOperationPermission(user, processInstance)) return Result.failed("操作失败，用户权限不足");
            //检查工作流是否为完成状态
            if (!processInstance.getState().typeIsFinished()) return Result.failed("实例运行中，不可操作");
            baseMapper.deleteById(processInstanceId);
            return Result.succeed("操作成功");
        } else return Result.failed("作业流实例不存在");
    }

    /**
     * 只有项目管理员和作业流执行人拥有修改权限
     *
     * @param user
     * @param processInstance
     * @return
     */
    private boolean checkOperationPermission(SysUser user, ProcessInstance processInstance) {
        if (user.getCurrentProjectId().equals(processInstance.getProId()) && UserRoleUtil.checkProAdmin(user.getProRoles()))
            return true;
        if (processInstance.getUsername().equals(user.getUsername())) return true;
        return false;
    }
}
